package com.corn.turtorial.provider.service;

import com.corn.turtorial.consumer.mapper.Point;
import com.corn.turtorial.consumer.service.PointService;
import com.corn.turtorial.provider.mapper.UserMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author : Jim Wu
 * @version 1.0
 * @function :
 * @since : 2022/5/5 11:01
 */

@Service
@Slf4j
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PointService pointClient;

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    @GlobalTransactional
    public void create(String username) {
        log.info("Seata全局事务id=================>{}", RootContext.getXID());

        User user = new User();
        user.setName(username);
        userMapper.insert(user);
        // 增加积分
        Point point = new Point();
        point.setUserId(user.getId());
        point.setPoint(atomicInteger.incrementAndGet());
        pointClient.createPoint(point);

//        int i = 1/0;
    }

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Transactional
    public void createWithTransactionMessage(String username) throws JsonProcessingException {
        User user = new User();
        user.setId(ThreadLocalRandom.current().nextLong(1000));
        user.setName(username);
        String userJson = objectMapper.writeValueAsString(user);
        //destination destination formats: `topicName:tags`
        Message<String> message = MessageBuilder.withPayload(userJson).build();
        TransactionSendResult sendResult = rocketMQTemplate.sendMessageInTransaction("txMsg:user", message, null);
//        int i = 1/0;
        log.info("send tx message body={},result= {}", message.getPayload(), sendResult.getSendStatus());
    }
}
